package com.chuantou.yuba.api.serializer;

import java.lang.reflect.Type;

import com.chuantou.yuba.api.to.BaseNewsTypeTO;
import com.chuantou.yuba.api.to.NewsCommentTO;
import com.chuantou.yuba.api.to.NewsImageContentTO;
import com.chuantou.yuba.api.to.NewsTextContentTO;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;

public class NewsDetailSerializer implements JsonDeserializer<BaseNewsTypeTO> {
	private Gson mGson;

	public NewsDetailSerializer() {
		GsonBuilder gsonb = new GsonBuilder();
        gsonb.serializeNulls();
        mGson = gsonb.create();
	}

	@Override
	public BaseNewsTypeTO deserialize(JsonElement element, Type type, JsonDeserializationContext context) throws JsonParseException {
		JsonObject obj = element.getAsJsonObject();
		JsonElement typeElement = obj.get(BaseNewsTypeTO.NAME_TYPE);
		BaseNewsTypeTO to = null;
		if (type != null) {
			String typeString = typeElement.getAsString();
			if (BaseNewsTypeTO.TYPE_IMAGE.equals(typeString)) {
				to = mGson.fromJson(element, NewsImageContentTO.class);
			} else if (BaseNewsTypeTO.TYPE_TEXT.equals(typeString)) {
				to = mGson.fromJson(element, NewsTextContentTO.class);
			}
		}
		if (to == null) {
			to = mGson.fromJson(element, NewsCommentTO.class);
		}
		return to;
	}

}
